package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.LoginDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMappper;

    @Override
    public R login(HttpServletRequest request, LoginDto loginDto) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", loginDto.getPhone());
        User user = userMappper.selectOne(queryWrapper);
        if (user == null) {
            user = new User();
            user.setPhone(loginDto.getPhone());
            userMappper.insert(user);
        }
        String phone = loginDto.getPhone();
        String attribute = (String) request.getSession().getAttribute(phone);
        if (!attribute.equals(loginDto.getCode())) {
            return R.error("验证码错误或者手机号码不一致");
        }
        request.getSession().setAttribute("user", user.getId());
        return R.success("登陆成功");
    }

    @Override
    public R loginOut(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }

    @Override
    public User getById(Long userId) {
        return userMappper.selectById(userId);
    }
}
